package com.fyx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyx.config.EighthMongoConfig;
import com.fyx.config.FourthMongoConfig;
import com.fyx.config.RequestConfig;
import com.fyx.entity.*;
import com.fyx.mapper.AnchorInfoMapper;
import com.fyx.mapper.SysDictDetailMapper;
import com.fyx.mapper.WechatUserMapper;
import com.fyx.service.ICheckService;
import com.fyx.until.HttpUtil;
import com.fyx.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CheckServiceImpl extends ServiceImpl<SysDictDetailMapper, SysDictDetail>  implements ICheckService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = FourthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fourthMongoTemplate;

    @Resource(name = EighthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate eighthMongoTemplate;

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Override
    public Map toCheck(CheckListEntity checkListEntity, Pageable pageable) {
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        query.with( Sort.by(Sort.Direction.ASC,"status"));
        query.with( Sort.by(Sort.Direction.DESC,"submit_time"));
        Criteria criteria = new Criteria();
        query.addCriteria(criteria);
        if (StringUtils.isNotBlank(checkListEntity.getUserid())){
            criteria.and("userid").is(checkListEntity.getUserid());
        }

        if (StringUtils.isNotBlank(checkListEntity.getStatus())){
            criteria.and("status").is(checkListEntity.getStatus());
        }

        if (checkListEntity.getMail_type()!=0){
            criteria.and("mail_type").is(checkListEntity.getMail_type());
        }

        if (checkListEntity.getMail_stype()!=0){
            criteria.and("mail_stype").is(checkListEntity.getMail_stype());
        }
        if(checkListEntity.getAnchors()!=null&&checkListEntity.getAnchor()){
            criteria.and("anchors").regex("anchor_12am");
            criteria.and("anchor").is(true);
        }

        if (checkListEntity.getQTime()!=null){
            criteria.andOperator(Criteria.where("submit_time").gte(checkListEntity.getQTime().get(0).getTime()/1000).lte(checkListEntity.getQTime().get(1).getTime()/1000));
        }

        List<CheckListEntity> list = mongoTemplate.find(query, CheckListEntity.class);
        long total = mongoTemplate.count(query, CheckListEntity.class);


        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public Map myCheckList(CheckListEntity checkListEntity, Pageable pageable) {
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        criteria.and("submit_userId").is(SecurityUtils.getCurrentUserId().toString());
        query.addCriteria(criteria);
        if (StringUtils.isNotBlank(checkListEntity.getUserid())){
            criteria.and("userid").is(checkListEntity.getUserid());
        }

        if (checkListEntity.getQTime()!=null){
            criteria.andOperator(Criteria.where("submit_time").gte(checkListEntity.getQTime().get(0).getTime()/1000).lte(checkListEntity.getQTime().get(1).getTime()/1000));
        }
        query.with( Sort.by(Sort.Direction.ASC,"status"));
        query.with( Sort.by(Sort.Direction.DESC,"submit_time"));
        List<CheckListEntity> list = mongoTemplate.find(query, CheckListEntity.class);
        long total = mongoTemplate.count(query, CheckListEntity.class);


        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }
    @Autowired
    private AnchorInfoMapper anchorInfoMapper;



    @Override
    public void checkPass(CheckListEntity checkListEntity) {
        Update update = new Update();
        update.set("check_time",(int) (new Date().getTime()/1000));
        update.set("check_reason",checkListEntity.getCheck_reason());
        update.set("check_userId", SecurityUtils.getCurrentUserId());
        update.set("check_userName", SecurityUtils.getCurrentUsername());
        if(checkListEntity.getAnchor()!=null&&checkListEntity.getAnchor()) {
            update.set("end_time", (new Date().getTime() / 1000) + 168 * 3600);
        }
        update.set("status","1");
        fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(checkListEntity.get_id())),update, CheckListEntity.class);
        if(checkListEntity.getAnchorInfoId()!=null&&checkListEntity.getAnchorInfoId()>0){
            QueryWrapper<AnchorInfo> wrapper=new QueryWrapper<>();
            wrapper.eq("id",checkListEntity.getAnchorInfoId());
            AnchorInfo anchorInfo=new AnchorInfo();
            anchorInfo.setStatus(2);
            anchorInfoMapper.update(anchorInfo,wrapper);
        }
            Thread t = new Thread(new Runnable() {
                public void run() {
                    for(int i=0;i<checkListEntity.getUserid().split(",").length;i++){
//                        if(!checkListEntity.getUserid().split(",").equals("")){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("p_id", checkListEntity.getUserid().split(",")[i]);
                            jsonObject.put("title", checkListEntity.getTitle());
                            jsonObject.put("content", checkListEntity.getContent());
                            jsonObject.put("mail_type", checkListEntity.getMail_stype());
                            jsonObject.put("award", checkListEntity.getAwards());
                            if(checkListEntity.getAnchor()!=null&&checkListEntity.getAnchor()) {
                                jsonObject.put("end_time",(new Date().getTime()/1000)+168*3600);
                            }
                            JSONObject map = new JSONObject();
                            map.put("cmd", "send_mail");
                            map.put("args", jsonObject);
                            try {
                                if(checkListEntity.getFlag()!=null&&checkListEntity.getFlag().equals("clmj")){
                                    HttpUtil.post(RequestConfig.baseRequestUrl2, map.toJSONString(), "utf-8");
                                }
                                else{
                                    HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
//                        }
                    }
                }
            });
            t.start();

    }

    @Override
    public void checkAllPass(CheckListEntity checkListEntity) {
        Update update = new Update();
        update.set("check_time",(int) (new Date().getTime()/1000));
        update.set("check_reason",checkListEntity.getCheck_reason());
        update.set("check_userId", SecurityUtils.getCurrentUserId());
        update.set("check_userName", SecurityUtils.getCurrentUsername());
        update.set("status","1");
        fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(checkListEntity.get_id())),update, CheckListEntity.class);

        GroupMailEntity groupMailEntity = new GroupMailEntity();
        groupMailEntity.setGroup_mailId((int) (new Date().getTime()/1000));
        groupMailEntity.setTitle(checkListEntity.getTitle());
        groupMailEntity.setContent(checkListEntity.getContent());
        groupMailEntity.setMail_type(checkListEntity.getMail_type());
        groupMailEntity.setMail_stype(checkListEntity.getMail_stype());
        groupMailEntity.setAttachment(checkListEntity.getAwards());
        groupMailEntity.setBegin_time(checkListEntity.getBegin_time());
        groupMailEntity.setEnd_time(checkListEntity.getEnd_time());
        groupMailEntity.setChannels(checkListEntity.getChannels());
        groupMailEntity.setVip(checkListEntity.getNobles());
        if(checkListEntity.getFlag()!=null&&checkListEntity.getFlag().equals("clmj")){
            eighthMongoTemplate.insert(groupMailEntity);
        }
        else {
            fourthMongoTemplate.insert(groupMailEntity);
        }
    }

    @Override
    public void checkNotPass(CheckListEntity checkListEntity) {
        Update update = new Update();
        update.set("check_time",(int) (new Date().getTime()/1000));
        update.set("check_reason",checkListEntity.getCheck_reason());
        update.set("check_userId", SecurityUtils.getCurrentUserId());
        update.set("check_userName", SecurityUtils.getCurrentUsername());
        update.set("status","2");
        if(checkListEntity.getAnchors()!=null&&checkListEntity.getAnchors().equals("anchor_12am_10")){
            update.set("anchors","");
        }
        fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(checkListEntity.get_id())),update, CheckListEntity.class);
    }
    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;

    public List<SysDictDetail> getDictId(long dictId){
        QueryWrapper<SysDictDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_id",dictId);
        List<SysDictDetail> list =sysDictDetailMapper.selectList(wrapper);
        return list;
    }

    @Override
    public void editCheckInfo(CheckListEntity checkListEntity){
        checkNotPass(checkListEntity);
        List<SysDictDetail> propsDictDictList = getDictId(10);
        String awardsContent="";
        checkListEntity.set_id(null);
        awardsContent=checkListEntity.getContent();
        if(checkListEntity.getMail_stype()==3){
            checkListEntity.setAwards(null);
        }else{
            List<AwardsEntity> awards =checkListEntity.getAwards();
            for(AwardsEntity awardsEntity:awards){
                String id =String.valueOf(awardsEntity.getId());

                if(id.equals("0")||StringUtils.isEmpty(id)){
                    checkListEntity.setAwards(null);
                }else {
                    String name = "";
                    String num = awardsEntity.getNum() + "";
                    for (SysDictDetail SysDictDetail : propsDictDictList) {
                        if (id.equals(SysDictDetail.getValue())) {
                            name = SysDictDetail.getLabel();
                            awardsContent += id + name + ":" + num + ",";
                        }
                    }
                }
            }
        }
        checkListEntity.setStatus("0");
        checkListEntity.setAwardsContent(awardsContent);
        checkListEntity.setSubmit_time((int) (new Date().getTime()/1000));
        checkListEntity.setSubmit_userName(SecurityUtils.getCurrentUsername());
        checkListEntity.setSubmit_userId(SecurityUtils.getCurrentUserId().toString());
        if(checkListEntity.getMailTime()!=null){
            checkListEntity.setBegin_time(checkListEntity.getMailTime().get(0).getTime()/1000-8*3600);
            checkListEntity.setEnd_time(checkListEntity.getMailTime().get(1).getTime()/1000-8*3600);
        }
        fourthMongoTemplate.insert(checkListEntity);
    }

    @Override
    public void checkCancel(CheckListEntity checkListEntity) {
        Update update = new Update();
        update.set("check_time",(int) (new Date().getTime()/1000));
        update.set("check_reason",checkListEntity.getCheck_reason());
        update.set("check_userId", SecurityUtils.getCurrentUserId());
        update.set("check_userName", SecurityUtils.getCurrentUsername());
        update.set("status","3");
        fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(checkListEntity.get_id())),update, CheckListEntity.class);
    }

    @Override
    public void bufaGuanzhuGift() {
        List<WechatUser>  list = wechatUserMapper.getList("false");
        String[] unionIds = new String[list.size()];
        for(int i=0;i<list.size();i++ ){
            unionIds[i]=list.get(i).getUnionid();
        }

        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("unionid").in(unionIds));
        query.addCriteria(criteria);
        List<UserEntity> list1 = mongoTemplate.find(query, UserEntity.class);
        for(UserEntity userEntity:list1){
            WechatUser wechatUser = new WechatUser();
            wechatUser.setGameid(userEntity.getUserid());
            wechatUser.setIssend("true");
            wechatUser.setUnionid(userEntity.getUnionid());
            wechatUserMapper.updateUnionId(wechatUser);
            Thread t = new Thread(new Runnable(){
                public void run(){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("pid",userEntity.getUserid());
                    jsonObject.put("result",true);
                    JSONObject map = new JSONObject();
                    map.put("cmd","binding_xixi");
                    map.put("args",jsonObject);

                    try {
                        HttpUtil.post(RequestConfig.baseRequestUrl2, map.toJSONString(),"utf-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }});

            t.start();
        }
    }

}
